import redis
import time
import os
import sys

# 针对无法通过环境变量设置合适的PYTHONPATH时的解决方案
sys.path.insert(0, '/home/peiyp/code')  # 把需要的PYTHONPATH直接放入sys.path的开头
from PyCmpltrtok.common import uuid, to_decode, sep


def text_gen(rdb, xinput, username=''):
    # 产生uuid
    xuuid = uuid()
    print('UUID:', xuuid)

    # 放入输入到hash，放入uuid到队列启动运算
    rdb.hset('uuid2input', xuuid, xinput.encode('utf8'))
    rdb.hset('uuid2username', xuuid, username.encode('utf8'))
    rdb.lpush('queue', xuuid)

    return xuuid

    """下面的逻辑暂时废弃"""

    # 等待输出
    while True:
        xoutput = rdb.hget('uuid2output', xuuid)
        if xoutput is None:
            time.sleep(0.001)
            continue
        xoutput = xoutput.decode('utf8')
        print('output:', xoutput)
        break

    # 清理数据
    rdb.hdel('uuid2input', xuuid)
    rdb.hdel('uuid2username', xuuid)

    # 返回结果
    return xoutput


if '__main__' == __name__:
    
    def _main():
        print('Unit test for daemon. Input q to quit.')
        
        xdefault_userid = 'user001'
        print(f'Which userid to use? (default: {xdefault_userid}): ')
        xuserid = input().strip()
        if not xuserid:
            xuserid = xdefault_userid
        print(f'OK, user is {xuserid}')
        
        # 连接Redis
        rdb = redis.Redis(os.environ['R_HOST'], int(os.environ['R_PORT']), 0)
        rdb.get('try_it')
        
        while True:
            print('Input: (Input q to quit.)')
            xinput = input().strip()
            if  'q' == xinput.lower():
                print('Bye!')
                break
            
            text_gen(rdb, xinput, xuserid)
            
            cnt = 0
            while True:
                cnt += 1
                time.sleep(0.2)
                
                # 最后结果
                xoutput = rdb.hget('username2output', xuserid)
                
                # 如果还没有结束
                if xoutput is None:  # 结束
                    sep(cnt)
                    xres = rdb.hget('username2dynamic', xuserid)
                    xres = to_decode(xres)
                    print(xres)
                    continue
                
                # 已经结束
                sep('end')
                xoutput = xoutput.decode('utf8')
                print(xoutput)
                break

    _main()
    